<?php
/**
 * 系统管理
 */
namespace app\htsoft\controller;
use think\Controller;
use think\Url;
use think\Config;
use think\Page;
use think\Verify;
use think\Db;
class System extends \app\common\controller\Base {
	
	
    function _initialize() {
        parent::_initialize();
    }
    /**
     * 清除缓存
     */
    public function clearcache(){
        clear_cache();
        adminLog2('清除了系统缓存');
    	return $this->fetch();
    }

    //获取子地区
    public function getchildarea() {
        $map=[];
        $id=input('parent_id');
        $select_id=input('select_id');
        if ($id){
            $map['pid'] = input('parent_id');
        }
        $area = Db::name('city')->field('id,name,pid') ->where($map)->order('sort asc')-> select();
        if ($area) {
            $option = '<option value="">---请选择---</option>';
            foreach ($area as $key => $value) {
                if($value['id']==$select_id){
                    $option = '<option selected="selected" value="'.$value['id'].'">'.$value['name'].'</option>';
                }else{
                    $option .= '<option value="'.$value['id'].'">'.$value['name'].'</option>';
                }

            }
            echo json_encode(array('error' => 0, 'option' => $option));
        } else {
            echo json_encode(array('error' => 1));
        }
    }
    public function hospitalinfo(){
        if(IS_POST){
            $posts = input("post.");
            $posts['id'] = 1;
            $arr=explode(',',$posts['lng_lat']);
            unset($posts['lng_lat']);
            $posts['lng']=$arr[0];
            $posts['lat']=$arr[1];
            $rst = Db::name('hospital') -> update($posts);
            adminLog2("变更医院信息!");
            $this -> success("保存成功!");
        }else{
            $province=Db::name('city')->field('id,name')->where(['pid'=>0])->select();
            $city=Db::name('city')->field('id,name')->select();
            $msg = Db::name('hospital') -> find(1);
            $this -> assign("province",$province);
            $this -> assign("city",$city);
            $this -> assign("hospital",$msg);
            return $this->fetch();
        }
    }
    /**
     * 
     * 系统参数设置
     */
    public function system(){
    	if(IS_POST){
    		$posts = input("post.");
    		$id['id'] = 1;
    		$rst = model('Options')->allowField(true)  -> save($posts,$id);
    		adminLog2("变更系统设置参数!");
    		$this -> success("保存成功!");
    	}else{
    		$msg = Db::name('options') -> find(1);
    		$this -> assign("msg",$msg);
    		return $this->fetch();
    	}
    }
    
    /**
     * 地区管理
     */
    public function address(){
    	$nowpage = input('page', 1, 'intval');
    	$limits = input('limits',10, 'intval');
    	$count = Db::name('district')->where(["level"=> 1]) -> order("id")   -> count();
    	$allpage = intval(ceil($count / $limits) );	if($nowpage > $allpage){$nowpage = $allpage;}
    	 
    	$level1 = Db::name('district') -> where(["level"=> 1]) -> page($nowpage, $limits) -> order("id") -> column("id");
    	$level2 = Db::name('district') -> where(["upid"=>["in",$level1],"level"=>2])  -> cache(true) -> column("id");
    	$id['id'] = array(array("in",$level1),array("in",$level2),"or");
    
    	$result = Db::name('district') ->  where($id) -> order("id") -> cache(true) -> select();
    	import("Tree");
    	$tree = new \think\Tree();
    	$tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
    	$tree->nbsp = '&nbsp;&nbsp;&nbsp;';
    	$newmenus=array();
    	foreach ($result as  &$m){
    		$m['parentid']=$m['upid'];
    		$newmenus[$m['id']]=$m;
    	}
    	foreach ($result as $n=> $r) {
    		$result[$n]['level'] = $this->_get_level($r['id'], $newmenus);
    		$result[$n]['parentid_node'] = ($r['upid']) ? ' class="child-of-node-' . $r['upid'] . '"' : '';
    		$add = "iframe('".Url::build("system/addressaddedit",["upid"=>$r['id'],"level"=>$r['level']])."','添加子地区','500px','230px')";
    		$edit = "iframe('".Url::build("system/addressaddedit",["id" =>$r['id']])."','编辑地区','500px','230px')";
    		if($r['level']== 2){
    			$result[$n]['str_manage'] = '<a onclick="'.$edit.'" class="layui-btn layui-btn-danger layui-btn-xs" >编辑地区</a>
	    					 								 <a data-url="'.Url::build("system/addressdelete",["id" => $r['id']]).'" class="layui-btn layui-btn-primary layui-btn-xs J_list_delete">删除地区</a> ';
    		}else{
    			$result[$n]['str_manage'] = '<a onclick="' .$add. '" class="layui-btn  layui-btn-normal layui-btn-xs">添加子地区</a>
	    													  <a onclick="' .$edit. '" class="layui-btn layui-btn-danger layui-btn-xs" >编辑地区</a>
	    													  <a data-url="'.Url::build("system/addressdelete",["id"=>$r['id']]).'" class="layui-btn layui-btn-primary layui-btn-xs J_list_delete">删除地区</a> ';
    		}
    		//显示切换开关
    		$url1 = Url::build('System/addressstatus',['id'=>$r['id']]);
    		$id = $r['id'];
    		$show0 = "<input type='checkbox' data-action='$url1'  lay-skin='switch' id='$id' lay-filter='category' lay-text='显示|隐藏'  title='开关' >";
    		$show1 = "<input type='checkbox' data-action='$url1'  lay-skin='switch' id='$id' lay-filter='category' lay-text='显示|隐藏'  title='开关'  checked>";
    		$result[$n]['is_open'] = $r['is_open'] ? $show0:$show1;
    	}
    	$tree->init($result);
    	$str = "<tr id='node-\$id' \$parentid_node>
						<td style='padding-left:20px;'>\$id</td>
						<td style='text-align:left;'>\$spacer\$name</td>
						<td>\$is_open</td>
						<td>\$str_manage</td>
					</tr>";
    	$categorys = $tree->get_tree(0, $str);
		$this -> assign("categorys", $categorys);
    	$this -> assign('allpage', $allpage);
    	$this -> assign('nowpage', $nowpage);
    	$this -> assign('allcount', $count);
    	$this -> assign('limits', $limits);
    	$this -> assign('formget', $_GET);
    	return $this -> fetch();
    }
    /**
     * 获取菜单深度
     * @param $id
     * @param $array
     * @param $i
     */
    protected function _get_level($id, $array = array(), $i = 0) {
    	if ($array[$id]['parentid']==0 || empty($array[$array[$id]['parentid']]) || $array[$id]['parentid']==$id){
    		return  $i;
    	}else{
    		$i++;
    		return $this->_get_level($array[$id]['parentid'],$array,$i);
    	}
    }
    
    /**
     * 添加新地区
     */
    public function addressaddedit()
    {
    	if(IS_POST){
    		$posts = input("post.");
    		if(!$posts['name']){
    			$this->error("请填写地区名");
    		}
    		if($posts['id']){
    			//编辑
    			$rst = Db::name('district') -> update($posts);
    			if($rst){
    				sp_clear_cache();
    				$this->success("编辑成功",Url::build('system/address'));
    			}else{
    				$this->error("您未做任何变动或服务器繁忙，请稍后再试！");
    			}
    		}else{
    			//添加
    			if($posts['level'] > 0){
    				$posts['level'] = $posts['level']+1;
    			}else{
    				$posts['level'] = 1;
    			}
    			$rst = Db::name('district') -> insertGetId($posts);
    			if($rst){
    				sp_clear_cache();
    				$this->success("添加成功",Url::build('system/address'));
    			}else{
    				$this->error("服务器繁忙，请稍后再试！");
    			}
    		}
    	}else{
    		$id = input("id");
    		$upid = input("upid");
    		$level = input("level");
    		if($id > 0){
    			$msg = Db::name('district') -> find($id);
    			$this -> assign("msg",$msg);
    		}
    		if($upid > 0){
    			$this -> assign("upid",$upid);
    		}
    		if($level > 0){
    			$this -> assign("level",$level);
    		}
    		return $this -> fetch();
    	}
    }
    /**
     * 删除地区
     */
    public function addressdelete()
    {
    	$id = intval(input("id"));
    	$count = Db::name('district') -> where(["upid" => $id]) -> count();
    	if ($count > 0) {
    		$this->error("该地区下还有子地区，无法删除！");
    	}
    	if (Db::name('district') -> delete($id) !== false) {
    		sp_clear_cache();
    		$this->success("删除地区成功！");
    	} else {
    		$this->error("删除失败！");
    	}
    }
    /**
     * 地区显示设置
     */
    public function addressStatus(){
    	$id['id'] = intval(input('id'));
    	$is_show = Db::name("district") -> where($id) -> find();
    	$arr['is_open'] = abs($is_show['is_open'] - 1);
    	if($arr['is_open']  == 1){
    		$rst = Db::name("district") -> where($id) -> update($arr);
    		if($rst){
    			if($is_show['level'] == 1){
    				$result = Db::name("district") -> where(["upid"=>$id['id']]) -> update($arr);
    			}
    			if($is_show['level'] == 2){
    				sp_clear_cache();
    				$this -> success ("已成功隐藏显示该地区!");
    			}
    			sp_clear_cache();
    			echo json_encode(array("code"=> 2,'msg'=>'已成功隐藏该地区以及其所有子地区!'));
    		}else{
    			$this -> error ("切换失败,请重试!");
    		}
    	}else if($arr['is_open']  == 0){
    		if($is_show['level'] == 2 || $is_show['level'] == 3){
    			$is_open = Db::name("district") -> where(['id'=>$is_show['upid']]) -> value('is_open');
    			if($is_open == 1){
    				$this -> error("该地区父级已被禁用，无法启用！");
    			}
    		}
    		$rst = Db::name("district") -> where($id) -> update($arr);
    		if($rst){
    			sp_clear_cache();
    			$this -> success ("已成功显示该地区！");
    		}else{
    			$this -> error ("切换失败,请重试!");
    		}
    	}
    }
    
}